package com.bdroidovore.app;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.htmlcleaner.*;

import android.app.Activity;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SearchResult extends Activity {

	private static final String TABLE_PATH = "/html/body/table/tbody/tr/td[2]/table/tbody/tr[3]/td[2]/div/form/table";
	private static final String ALBUM_PATH = "//a[2]/strong/font";
	private static final String SERIE_PATH = "//a/strong/font";
	private static TagNode node;
	
	public SearchResult() throws IOException, XPatherException {
		// TODO Auto-generated constructor stub
		HtmlCleaner cleaner = new HtmlCleaner();
		CleanerProperties props = cleaner.getProperties();
		props.setAllowHtmlInsideAttributes(true);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);
		
		String SearchUrl = "http://www.bdovore.com/membres/search.php?str_search=spiderman&Submit=Envoyer&cb_album=cb_album&cb_serie=cb_serie&cb_aut=cb_aut";

		URL url = new URL(SearchUrl);
		URLConnection conn = url.openConnection();
		
		node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
	
		Object[] TableNode = node.evaluateXPath(TABLE_PATH);
		TagNode tTableNode = (TagNode)TableNode[0];
		Object[] LineNodes = tTableNode.evaluateXPath("/tbody/tr");
		
		Object[] Album;
		Object[] Serie;
		TagNode tAlbum;
		TagNode tSerie;
		String sSerie;
		String sAlbum;
		TextView vAlbum = new TextView(this);
		TextView vSerie = new TextView(this);
		
		this.setContentView(R.layout.searchresult);
		TableLayout t1 = (TableLayout)findViewById(R.id.tableResult);
		
		for(int i=0;i<=LineNodes.length;i++){
			TagNode CurLine = (TagNode)LineNodes[i];
			
			Album = CurLine.evaluateXPath(ALBUM_PATH);
			tAlbum = (TagNode)Album[0];
			
			Serie = CurLine.evaluateXPath(SERIE_PATH);
			tSerie = (TagNode)Serie[0];
			
			sAlbum = tAlbum.getChildren().iterator().next().toString().trim();
			sSerie = tSerie.getChildren().iterator().next().toString().trim();		
			
			TableRow tr = new TableRow(this);
			
			tr.setLayoutParams(new LayoutParams(
							LayoutParams.FILL_PARENT,
							LayoutParams.WRAP_CONTENT));
			
			vAlbum.setText(sAlbum);
			vSerie.setText(sSerie);
			
			tr.addView(vAlbum);
			tr.addView(vSerie);
			
			t1.addView(tr);
		}		
		
	}

}
